package com.etc.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONObject;
import com.etc.entity.Housers;
import com.etc.entity.Housing;
import com.etc.entity.jsonui.JsonUi;
import com.etc.service.HousingService;
import com.etc.service.impl.HousingServiceImpl;
import com.etc.util.PageData;
import com.google.gson.Gson;

/**
 * Servlet implementation class AdminsHousingServlet
 */
@WebServlet("/hs.do")
public class AdminsHousingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private HousingService housingService = new HousingServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    

	// 保存文件的目录
	private static String PATH_FOLDER = "/";
	// 存放临时文件的目录
	private static String TEMP_FOLDER = "/";

	/**
	 * Destruction of the servlet. <br>
	 */

    
    public AdminsHousingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String op= "query";
		if (request.getParameter("op")!=null) {
			op=request.getParameter("op");
		}
		if (op.equals("query")) {
			PageDoQuery(request, response);
		}
		else if (op.equals("update")) {
			//这时候用的是request.getReader();这个方法是用于获取页面一侧的ajax请求中的Json数据
		    BufferedReader reader= request.getReader();
		    //用字符串拼接的方式来拼接接收到的JSON数据
		    StringBuffer sBuffer = new StringBuffer();
		    //定义一个字符串让他为空，在下面的while循环中不断赋予它值，使得字符串可以拼接
		    String str = null;
		    while((str=reader.readLine())!=null) {
		    	sBuffer.append(str);
		    }
		    System.out.println(sBuffer);
		    //将GSON数据转化成Users对象，方便后面传入数据库
		    Gson gson = new Gson();
		    //转换对象的方式，并赋予users
		    Housing housing= gson.fromJson(sBuffer+"",Housing.class);
		    System.out.println(housing);
		    
//		    int id =Integer.parseInt(request.getParameter("id"));
		    
		    String hsPic01 = "..//imgs//housing//" + request.getSession().getAttribute("filename1");
			String hsPic02 = "..//imgs//housing//" + request.getSession().getAttribute("filename2");
			String hsPic03 = "..//imgs//housing//" + request.getSession().getAttribute("filename3");
		    
		    boolean flag =housingService.UpdateHousingTwice(housing, hsPic01, hsPic02, hsPic03);
		    PrintWriter out = response.getWriter();
			out.print(flag);
//			out.close();
			System.out.println(flag);
		}else if(op.equals("add")) {
			String houseName = request.getParameter("houseName");
			String houseType = request.getParameter("houseType");
			String hsTiele = request.getParameter("hsTiele");
			int hsPrice = Integer.parseInt(request.getParameter("hsPrice"));
			int hsArea = Integer.parseInt(request.getParameter("hsArea"));
			String hsAddress = request.getParameter("hsAddress");
			String hsCall = request.getParameter("hsCall");
			String hsWechat = request.getParameter("hsWechat");
			String hsIntroduce = request.getParameter("hsIntroduce");
			
			String hsPic01 = "..//imgs//housing//" + request.getSession().getAttribute("filename1");
			String hsPic02 = "..//imgs//housing//" + request.getSession().getAttribute("filename2");
			String hsPic03 = "..//imgs//housing//" + request.getSession().getAttribute("filename3");
			int hsRemain = Integer.parseInt(request.getParameter("hsRemain"));
			
			Housing housing = new Housing(houseName, houseType, hsTiele, hsPrice, hsArea, hsAddress, hsCall, hsWechat, hsIntroduce, hsPic01, hsPic02, hsPic03, hsRemain);
			boolean flag = housingService.AddHousing(housing);
			request.getRequestDispatcher("admin_housing.jsp").forward(request, response);
			
			PrintWriter out = response.getWriter();
			out.print(flag);
			out.close();
		}
		else if(op.equals("removesession")) {

			request.getSession().invalidate();
			request.getRequestDispatcher("index.jsp").forward(request, response);
			
		}
	}

	private void PageDoQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		int page =1;
		if (request.getParameter("page")!=null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		int limit =10;
		if (request.getParameter("limit")!=null) {
			limit = Integer.parseInt(request.getParameter("limit"));
		}
		String strLike="";
		if (request.getParameter("strLike")!=null) {
			strLike =request.getParameter("strLike");
		}
		
		PageData<Housing> pd  = housingService.getHousingAll(page, limit, strLike);
		
		JsonUi<Housing> jsonUi = new JsonUi<>(0, "", pd.getTotalCount(), pd.getData());
		
		Gson gson = new Gson();
		String string = gson.toJson(jsonUi);
		out.println(string);
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	}



